#!/usr/bin/python3
# -*- coding: utf-8 -*-


import os
import sys
import pymysql
import time
import datetime


from flask import Flask,jsonify,request,abort,json
from contro.log import *
from conf.config import CONF


soft_pach= sys.path[0]


# db = pymysql.connect(host=CONF.SQL.SQLServerIP,user=CONF.SQL.SQLServerUser,passwd=CONF.SQL.SQLServerPasswd,db=CONF.SQL.SQLServerDatabase)
# db.autocommit(True)
# cur = db.cursor()

########fio
# set a fio command
def SSH_FIO_CMD(name, type, filename, bs):
    ssh_command = "'fio -filename=" + filename + " -direct=1 -iodepth 1 -thread -rw=" + type + " -ioengine=psync -bs=" + bs + " -size=4096M -numjobs=20 -runtime=10 -group_reporting -name=" + name + "  --output-format=json'"
    logging.debug("fio command:" + ssh_command)
    return (ssh_command)

#######qos
# set a iperf3 command
def SSH_QOS_CMD(server):
    ssh_command = "'iperf3 -c  "+ server +"   -t 10 -J'"
    logging.debug("qos command:" + ssh_command)
    return (ssh_command)



########public def
def Detect_sshpass():
    # cheakc sshpass
    return os.path.exists('/usr/bin/sshpass')


# use ssh connect host, run command and create a report output to one file
def SSH_CMD(ssh_ipaddr, ssh_command, date):
    user,passwd=CONF.CLIENT.ClientHostUser,CONF.CLIENT.ClientHostPasswd
    output_filename = soft_pach + '/output/' + date + '_' + ssh_ipaddr
    if Detect_sshpass()==True:
        cmd = 'sshpass -p '+passwd+' ssh '+user+'@'+ssh_ipaddr+' -o StrictHostKeyChecking=no  '+ ssh_command + ' > '+ output_filename
        logging.debug("ssh cmd:" + cmd)
        os.system(cmd)
    else:
        error='Please run "apt-get install sshpass -y"'
        logging.error(error)
        return error



# read report, return a json
def READ_OUTPUT(ssh_ipaddr,date):
    time.sleep(3)
    output_filename = soft_pach + '/output/' + date + '_' + ssh_ipaddr
    logging.debug("read output file:" + output_filename)
    file_content = open(output_filename, encoding='utf-8')
    report = json.load(file_content)
    return report



######## fio test
def FORMAT_FIO_REPORT(report,type, date):
    fio_version = report['fio version']
    time = date
    fio_time = report['time']
    fio_bs = report['global options']['bs']
    fio_type = report['global options']['rw']
    fio_filename = report['global options']['filename']
    fio_job_name = report['jobs'][0]['jobname']
    if 'randwrite' in type:
        fio_write_bw = report['jobs'][0]['write']['bw']
        fio_write_iops = report['jobs'][0]['write']['iops']
        describe = "write_bw Use KB as the unit"
        REPORT={"test_type": "storage",
                "time": time, 
                'fio version': fio_version, 
                'bs': fio_bs, 
                "fio time": fio_time,
                "type": fio_type, 
                "filename": fio_filename, 
                "name": fio_job_name,
                "write_bw": fio_write_bw, 
                "write_iops": fio_write_iops, 
                "describe": describe}
        return REPORT
    elif 'randrw' in type:
        fio_read_bw = report['jobs'][0]['read']['bw']
        fio_read_iops = report['jobs'][0]['read']['iops']
        fio_write_bw = report['jobs'][0]['write']['bw']
        fio_write_iops = report['jobs'][0]['write']['iops']
        describe = "write_bw and read_bw Use KB as the unit"
        REPORT={"test_type": "storage",
                "time": time, 
                'fio version': fio_version, 
                'bs': fio_bs, "fio time": fio_time,
                "type": fio_type, 
                "filename": fio_filename, 
                "name": fio_job_name,
                "read_bw": fio_read_bw, 
                "read_iops": fio_read_iops, 
                "write_bw": fio_write_bw,
                "write_iops": fio_write_iops, 
                "describe": describe}
        return REPORT
    else:
        return {"ERROR": "This type of report is not supported"}



def FIO_TEST(name, type, filename, bs, host):
    date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    ssh_command = SSH_FIO_CMD(name, type, filename, bs)
    all_report = []
    dic = {}
    for i in host:
        ssh_ipaddr = i
        SSH_CMD(ssh_ipaddr, ssh_command, date)
        report = READ_OUTPUT(ssh_ipaddr, date)
        one_host_report = FORMAT_FIO_REPORT(report, type,date)
        all_report.append(one_host_report)
    for keys ,values in zip(host,all_report):
        values = values
        dic[keys] = values
    return dic



######## qos test
def FORMAT_QOS_REPORT(report, name, date):
    name = name
    iperf_version = report['start']['version']
    iperf_time= report['start']['timestamp']['time']
    connecting_to = report['start']['connecting_to']['host']
    bits_per_second = report['end']['sum_received']['bits_per_second']
    bits_per_second = round(bits_per_second/1000,10)
    connected=report['start']['connected']
    time = date
    REPORT={"test_type": "qos", 
            "time": time, 
            'iperf version': iperf_version, 
            "iperf time": iperf_time,
            "server": connecting_to, 
            "name": name, 
            "iperf_kbps": bits_per_second,
            "describe iperf_kbps": "The unit of use is 'Kbit'",
            "connection information": connected}
    return REPORT



def QOS_TEST(name, server, client):
    date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    ssh_ipaddr = client
    ssh_command =SSH_QOS_CMD(server)
    SSH_CMD(ssh_ipaddr, ssh_command, date)
    report = READ_OUTPUT(ssh_ipaddr, date)
    REPORT=FORMAT_QOS_REPORT(report, name,date)
    return REPORT






#
# ssh_ipaddr='172.16.0.xx'
# ssh_command="'fio -filename=/dev/vdb -direct=1 -iodepth 1 -thread -rw=write -ioengine=psync -bs=4k -size=4096M -numjobs=10 -runtime=10 -group_reporting -name=mytest  --output-format=json'"
#
#
# name, type, filename, bs = 'mytest', 'randwrite', '/dev/vdb', '4k'
# type = 'randrw'
# host= ['172.16.0.xx','172.16.0.xx']


